package com.flyduck.security;

import com.flyduck.common.exception.CaptchaException;
import com.flyduck.constant.RedisConstant;
import com.flyduck.utils.RedisUtils;
import com.flyduck.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 在UsernamePasswordAuthenticationFilter增加验证码得校验
 * </p>
 *
 * @author flyduck
 * @since 2024-05-28
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //登录请求，才拦截
        String uri = request.getRequestURI();
        if("/login".equals(uri) && request.getMethod().equals("POST")){
            try {
                //校验验证码
                validateCode(request);
            } catch (CaptchaException e) {
                //不正确，就跳转到认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request,response, e);
            }
        }
        filterChain.doFilter(request,response);
    }

    //校验验证码
    private void validateCode(HttpServletRequest request) {
        String uuid = request.getParameter("uuid");
        String code = request.getParameter("code");

        if(StringUtils.isBlank(uuid) || StringUtils.isBlank(code)){
            throw new CaptchaException("验证码错误");
        }

        if(!code.equals(redisUtils.hget(RedisConstant.LOGIN_CAPTCHA_KEY, uuid))){
            throw new CaptchaException("验证码错误");
        }

        //删除redis存储的验证码code，一次性使用
        redisUtils.hdel(RedisConstant.LOGIN_CAPTCHA_KEY,uuid);
    }
}
